package com.itheima.appserver.controller;

import com.itheima.appserver.config.NoAuthorization;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.appserver.service.SystemService;
import com.itheima.commons.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关API接口
 */
@RestController
@RequestMapping("/management/system/users")
public class SystemController {

    @Autowired
    private SystemService systemService;


    /**
     * 用户登录
     * @param params
     * @return
     */
    @PostMapping("login")
    @NoAuthorization
    public ResponseEntity adminLogin(@RequestBody Map<String, String> params,
                                     HttpServletResponse response) {
        Map map = systemService.checkUserLogin(params,response);
        return ResponseEntity.ok(map);
    }

    /**
     * 管理员登录验证码图片
     * @param params
     * @return
     */
    @GetMapping("verification")
    @NoAuthorization
    public void adminVerificationCode(@RequestParam Map<String, String> params,
                                                HttpServletResponse response) {
        systemService.adminVerificationCode(params.get("uuid"), response);
    }

    /**
     * 用户登出
     */
    @PostMapping("logout")
    public ResponseEntity adminLogout(HttpServletResponse response) {
        //跳转首页，并删除token,删除token
        try {
            response.sendRedirect("http://localhost:8080");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            UserThreadLocal.remove();
            Cookie cookie = new Cookie("admin_access_token", null);
            cookie.setMaxAge(0);
        }
        return ResponseEntity.ok(null);
    }
    /**
     * 管理员基本信息
     */
    @PostMapping("profile")
    public ResponseEntity adminProfile() {
        AdminVo adminVo = systemService.adminProfile();
        return ResponseEntity.ok(adminVo);
    }


}
